package com.forstudy.util;

import com.forstudy.common.Constants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BatchPreparedStatementSetter;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;

import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 *
 * @author: erdong
 * Date: 2020/4/15
 * Time: 22:00
 * Description: No Description
 */
public class MySqlUtil {

    @Autowired
    private JdbcTemplate jdbcTemplate;

    public void executeSql(String sql) {

        jdbcTemplate.execute(sql);
    }

    /**
     * 批处理，导入数据到数据库当中
     *
     * @param tag
     * @param tableName
     */
    public void importData(String tag, String tableName) {

        List<List<String>> datas = Constants.datas.get(tag);
        StringBuffer t_sql = new StringBuffer("insert into " + tableName + " values(" );
        int size = datas.get(0).size();
        for(int i=0; i<size;i++) {
            t_sql.append(" ?,");
        }
        String sql = t_sql.substring(0, t_sql.length() - 1) + ")";
        System.out.println("Current SQL : " + sql);
        jdbcTemplate.batchUpdate(sql, new BatchPreparedStatementSetter() {
            @Override
            public void setValues(PreparedStatement preparedStatement, int i) throws SQLException {
                List<String> data = datas.get(i);
                System.out.println(data.size());
                for(int j=0; j<size; j++) {
                    preparedStatement.setString(j+1, data.get(j));
                }
            }

            @Override
            public int getBatchSize() {
                return datas.size();
            }
        });
    }
}
